// 创建用户集合
const mongoose = require('mongoose')

const Joi = require('joi')

// 导入bcyrypt'模块
const bcrypt = require('bcrypt')

// 创建用户集合规则
const userSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 20,
    },
    email: {
        type: String,
        required: true,
        unique: true, // 保存邮箱地址在插入数据时不重复
    },
    password: { type: String, required: true },
    // admin 超管
    // normal 普通用户
    role: {
        type: String,
        require: true,
        default: 'normal',
    },
    // 0 启用 1 禁用
    state: {
        type: Number,
        default: 0,
    }
});

// 创建集合
const User = mongoose.model('User', userSchema);
async function createUser() {
    const salt = await bcrypt.genSalt(10)
    const password = await bcrypt.hash('123456', salt)
    await User.create({
        username: 'admin',
        email: 'admin@163.com',
        password,
        role: 'admin',
        state: 0,
    })
}

// createUser();

const validateUser = (user) => {
    const schema = Joi.object({
        username: Joi.string().min(2).max(12).required().error(new Error('用户名不符合规则')),
        email: Joi.string().email().required().error(new Error('邮箱不符合规则')),
        password: Joi.string().min(6).max(12).required().regex(/^[a-zA-Z0-9]{3,30}$/).error(new Error('密码不符合规则')),
        role: Joi.string().valid('normal', 'admin').required().error(new Error('角色非法')), // valid()表示role值必须在这中间选
        state: Joi.number().valid(0, 1).required().error(new Error('状态值非法'))
    })

    return Joi.validate(user, schema);
}

module.exports = {
    User,
    validateUser,
}